package com.igeek.boot.service;

import com.igeek.boot.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author fengqq
 * @Description 基于redisTemplate来添加数据 查询数据
 * @Date 2024/9/4  16:12
 *
 * opsForValue()  封装string字符串相关的操作命令对象
 * opsForZSet()   zset有序的集合
 * opsForSet()    set无序不重复数据类型
 * opsForHash()   哈希
 * opsForHyperLogLog()  基数统计
 * opsForList()     链表
 * opsForGeo()...   地理位置
 */
@Service
@Slf4j
public class OrdersService {

    //定制redis中存储数据的key的规则
    private static final String REDIS_OID = "oid::";


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //创建订单
    public Orders create() {
        //随机产生订单号 1
        int oid = ThreadLocalRandom.current().nextInt(1000);
        //随机产生流水号 abc
        String serial = UUID.randomUUID().toString();
        Orders orders = new Orders(oid, "流水号是"+serial);
        //在redis中存储订单对象 oid::1 {"oid":1,"serial":"流水号是abc"}
        redisTemplate.opsForValue().set(REDIS_OID+oid,orders);
        log.info("创建的orders:{}",orders);
        return orders;
    }

    //查看订单
    public Orders findOne(Integer orderId) {
        //从redis中 查看订单对象
        Object orders = redisTemplate.opsForValue().get(REDIS_OID + orderId);
        log.info("查询的orders:{}",orders);
        return (Orders) orders;
    }
}
